package com.lemon.smartsafetynew.ui.activity.base;

import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.ColorRes;
import android.support.annotation.IdRes;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.google.gson.Gson;
import com.lemon.smartsafety.BuildConfig;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.IApplication;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.ui.activity.voice.AudioRecorder;
import com.lemon.smartsafety.utils.GsonUtil;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.SharedPreferencesHelper;
import com.lemon.smartsafety.utils.common.FileUtil;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.utils.common.ViewUtils;
import com.lemon.smartsafety.view.tagview.Tag;
import com.lemon.smartsafety.view.tagview.TagView;
import com.lemon.smartsafetynew.util.common.CheckAppExist;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.FileCallBack;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import butterknife.ButterKnife;
import cn.finalteam.galleryfinal.permission.AfterPermissionGranted;
import cn.finalteam.galleryfinal.permission.EasyPermissions;
import okhttp3.Call;

/**
 * Created by Cooliean on 16/1/15.
 */
public abstract class BaseActivity extends AppCompatActivity implements MediaPlayer.OnCompletionListener,
        MediaPlayer.OnErrorListener, MediaPlayer.OnPreparedListener, EasyPermissions.PermissionCallbacks {

    private static final int PERMISSIONS_CODE = 1211;


    public static final String TAG = "BaseActivity";


    private LayoutInflater mInflater;

    public Gson mGson;

    private LemonPermissionListener mPermissionListener;

    /**
     * 提示信息对话框
     */
    public HUDUtil mHUDUtil;

    protected abstract void getBundleArgs();

    /**
     * 设置视图文件
     *
     * @return
     */
    protected abstract int getContentViewId();

    protected abstract void initViews();

    public SharedPreferencesHelper mSharedPreferencesHelper;
    private Method noteStateNotSavedMethod;
    private Object fragmentMgr;
    private String[] activityClassName = {"Activity", "FragmentActivity","AppCompatActivity"};
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        AppManager.getAppManager().addActivity(this);
        setContentView(getContentViewId());
        mHUDUtil = new HUDUtil();
        mHUDUtil = mHUDUtil.init(BaseActivity.this);
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        getBundleArgs();
        baseOnCreate(savedInstanceState);
        mSharedPreferencesHelper = new SharedPreferencesHelper(this);
        mGson = GsonUtil.getCommonGson();
        AppService.getInstance().getBus().register(this);
        ButterKnife.bind(this);
        initListener();
        initViews();
    }

    public void baseOnCreate(Bundle savedInstanceState) {

    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        invokeFragmentManagerNoteStateNotSaved();
    }

    private void invokeFragmentManagerNoteStateNotSaved() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            return;
        }
        try {
            if (noteStateNotSavedMethod != null && fragmentMgr != null) {
                noteStateNotSavedMethod.invoke(fragmentMgr);
                return;
            }
            Class cls = getClass();
            do {
                cls = cls.getSuperclass();
            } while (!(activityClassName[0].equals(cls.getSimpleName())
                    || activityClassName[1].equals(cls.getSimpleName())));

            Field fragmentMgrField = prepareField(cls, "mFragments");
            if (fragmentMgrField != null) {
                fragmentMgr = fragmentMgrField.get(this);
                noteStateNotSavedMethod = getDeclaredMethod(fragmentMgr, "noteStateNotSaved");
                if (noteStateNotSavedMethod != null) {
                    noteStateNotSavedMethod.invoke(fragmentMgr);
                }
            }

        } catch (Exception ex) {

        }
    }

    private Method getDeclaredMethod(Object object, String methodName, Class<?>... parameterTypes) {
        Method method = null;
        for (Class<?> clazz = object.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                method = clazz.getDeclaredMethod(methodName, parameterTypes);
                return method;
            } catch (Exception e) {
            }
        }
        return null;
    }

    private Field prepareField(Class<?> c, String fieldName) throws NoSuchFieldException {
        while (c != null) {
            try {
                Field f = c.getDeclaredField(fieldName);
                f.setAccessible(true);
                return f;
            } finally {
                c = c.getSuperclass();
            }
        }
        throw new NoSuchFieldException();
    }


    public LayoutInflater getInflater() {
        if (mInflater == null) {
            mInflater = LayoutInflater.from(this);
        }
        return mInflater;
    }

    /**
     * 是否是Android M （23版本号）
     *
     * @return
     */
    public boolean isAndroidM() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            return true;
        }
        return false;
    }

    //    public void checkPermission(String message, LemonPermissionListener listener, String... permissions) {
    //        checkPermission(message, getString(R.string.permission_denied_tip), listener, permissions);
    //    }
    //
    //    public void checkPermission(String message, String deniedMessage, LemonPermissionListener listener, String... permissions) {
    //        this.mPermissionListener = listener;
    //        new TedPermission(IApplication.context()).setPermissionListener(permissionlistener)
    //                                                 .setRationaleMessage(message)
    //                                                 .setDeniedMessage(deniedMessage)
    //                                                 .setPermissions(permissions)
    //                                                 .check();
    //
    //
    //    }

    public void checkPermission(String message, LemonPermissionListener listener, String... permissions) {
        checkPermission(message, getString(R.string.permission_denied_tip), listener, permissions);
    }

    @AfterPermissionGranted(PERMISSIONS_CODE)
    public void checkPermission(String message, String deniedMessage, LemonPermissionListener listener, String... permissions) {
        this.mPermissionListener = listener;
        if (EasyPermissions.hasPermissions(this, permissions)) {
            listener.onPermissionGranted(PERMISSIONS_CODE);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(this, message, PERMISSIONS_CODE, permissions);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // Forward results to EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> list) {
        this.mPermissionListener.onPermissionGranted(requestCode);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> list) {
        this.mPermissionListener.onPermissionDenied(requestCode, (ArrayList<String>) list);
    }


    protected void initListener() {


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHUDUtil != null) {
            mHUDUtil.hidden();
        }
        try {
            stopPlay();
            if (mMediaPlayer != null) {
                mMediaPlayer = null;
            }
        } catch (Exception e) {
        }
        AppService.getInstance().getBus().unregister(this);
        ButterKnife.unbind(this);
        setContentView(R.layout.view_null);
    }

    /**
     * 查找View
     *
     * @param id   控件的id
     * @param <VT> View类型
     * @return
     */
    protected <VT extends View> VT getViewById(@IdRes int id) {
        return (VT) findViewById(id);
    }

    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }


    /**
     * 显示菜单的ICON
     *
     * @param menu
     * @param enable
     */
    public void setIconEnable(Menu menu, boolean enable) {
        try {
            //未知的类  com.android.internal.view.menu.MenuBuilder
            Class<?> clazz = Class.forName("android.support.v7.view.menu.MenuBuilder");
            Method m = clazz.getDeclaredMethod("setOptionalIconsVisible", boolean.class);
            m.setAccessible(true);
            //MenuBuilder实现Menu接口，创建菜单时，传进来的menu其实就是MenuBuilder对象(java的多态特征)
            m.invoke(menu, enable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得一个顶部控件
     */
    public View getHeaderView(int message) {
        return getHeaderView(getString(message));
    }

    /**
     * 获得一个顶部控件
     */
    public View getHeaderView(String message) {
        View header = LayoutInflater.from(this)
                .inflate(R.layout.view_login_user_tip_head, (ViewGroup) findViewById(android.R.id.content), false);
        TextView headerView = (TextView) header;
        headerView.setTextColor(getResources().getColor(R.color.colorTextPrimary));
        headerView.setText(message);
        return headerView;
    }

    public String toJson(Object o) {
        return mGson.toJson(o);
    }

    public MaterialDialog.Builder getConfirmDialog(String content, MaterialDialog.SingleButtonCallback callback) {
        return new MaterialDialog.Builder(this).title(getString(R.string.tip_str_title))
                .content(content)
                .positiveText(R.string.sure_str)
                .negativeText(R.string.cancel_str)
                .onAny(callback);
    }


    /**
     * @param content
     * @param positiveText 点击确定的字符串
     * @param negativeText 点击取消的字符串
     * @param callback
     * @return
     */
    public MaterialDialog.Builder getConfirmDialog(String content, int positiveText, int negativeText, MaterialDialog.SingleButtonCallback callback) {
        return new MaterialDialog.Builder(this).title(getString(R.string.tip_str_title))
                .content(content)
                .positiveText(positiveText)
                .negativeText(negativeText)
                .onAny(callback);
    }


    public void replaceFragment(Fragment fragment) {
        replaceFragment(R.id.main_content, fragment);
    }

    public void replaceFragment(int fragmentId, Fragment fragment) {
        getSupportFragmentManager().beginTransaction()
                .replace(fragmentId, fragment, fragment.getClass().getName())
                .commit();
    }

    public void disableForm(View parentView) {

        List<View> views = getAllChildViews(parentView);
        for (int i = 0; views != null && i < views.size(); i++) {
            View view = views.get(i);
            view.setOnClickListener(null);
            if (view instanceof MaterialEditText) {
                MaterialEditText edit = (MaterialEditText) view;
                edit.setEnabled(false);
                edit.setShowClearButton(false);
                edit.setHideUnderline(true);
                edit.setHint("");
                edit.setMetTextColor(getResources().getColor(R.color.colorTextSecondary));
            } else if (view instanceof CheckBox) {
                CheckBox checkBox = (CheckBox) view;
                checkBox.setTextColor(getResources().getColor(R.color.colorTextSecondary));
                checkBox.setEnabled(false);
            }
        }
    }

    public void disableFormWithOutButton(View parentView) {

        List<View> views = getAllChildViews(parentView);
        for (int i = 0; views != null && i < views.size(); i++) {
            View view = views.get(i);
            if (view instanceof Button) {
                continue;
            }
            view.setOnClickListener(null);
            if (view instanceof MaterialEditText) {
                MaterialEditText edit = (MaterialEditText) view;
                edit.setEnabled(false);
                edit.setShowClearButton(false);
                edit.setHideUnderline(true);
                edit.setHint("");
                edit.setMetTextColor(getResources().getColor(R.color.colorTextSecondary));
            } else if (view instanceof CheckBox) {
                CheckBox checkBox = (CheckBox) view;
                checkBox.setTextColor(getResources().getColor(R.color.colorTextSecondary));
                checkBox.setEnabled(false);
            }
        }
    }

    public void disableEditText(MaterialEditText edit) {
        edit.setOnClickListener(null);
        edit.setEnabled(false);
        edit.setShowClearButton(false);
        edit.setHideUnderline(true);
        edit.setHint("");
        edit.setMetTextColor(getResources().getColor(R.color.colorTextSecondary));
    }

    /**
     * @note 获取该activity所有view
     */
    public List<View> getAllChildViews() {
        View view = this.getWindow().getDecorView();
        return getAllChildViews(view);
    }

    private List<View> getAllChildViews(View view) {
        List<View> allChildren = new ArrayList<View>();
        if (view instanceof ViewGroup) {
            ViewGroup vp = (ViewGroup) view;
            for (int i = 0; i < vp.getChildCount(); i++) {
                View viewChild = vp.getChildAt(i);
                allChildren.add(viewChild);
                allChildren.addAll(getAllChildViews(viewChild));
            }
        }
        return allChildren;
    }

    public List<MaterialEditText> getAllMaterialEditText(View view) {
        List<View> views = getAllChildViews(view);
        List<MaterialEditText> result = new ArrayList<>();
        for (int i = 0; i < views.size(); i++) {
            View viewChild = views.get(i);
            if (viewChild instanceof MaterialEditText) {
                result.add((MaterialEditText) viewChild);
            }
        }
        return result;
    }


    public List<CheckBox> getAllCheckBox(View view) {
        List<View> views = getAllChildViews(view);
        List<CheckBox> result = new ArrayList<>();
        for (int i = 0; i < views.size(); i++) {
            View viewChild = views.get(i);
            if (viewChild instanceof CheckBox) {
                result.add((CheckBox) viewChild);
            }
        }
        return result;
    }


    public void setTagView(TagView tagView, List<SelectDataI> items) {
        setTagView(tagView, items, R.color.orange, R.color.colorWhite, true);
    }

    public void setTagView(TagView tagView, List<SelectDataI> items, @ColorRes int layoutColor) {
        setTagView(tagView, items, layoutColor, true);
    }

    public void setTagView(TagView tagView, List<SelectDataI> items, @ColorRes int layoutColor, boolean canDelete) {
        setTagView(tagView, items, layoutColor, R.color.colorWhite, canDelete);
    }

    public void setTagView(TagView tagView, List<SelectDataI> items, @ColorRes int layoutColor, @ColorRes int textColor, boolean canDelete) {
        if (items.size() == 0) {
            tagView.removeAllTags();
        } else {
            tagView.removeAllTags();
            for (int i = 0; i < items.size(); i++) {
                Tag tag = new Tag(items.get(i).getTitle());
                tag.tagTextColor = getResources().getColor(textColor);
                tag.layoutColor = getResources().getColor(layoutColor);
                tag.layoutColorPress = getResources().getColor(layoutColor);
                tag.radius = 15f;
                tag.tagTextSize = ViewUtils.px2dip(this, getResources().getDimensionPixelSize(R.dimen.common_text_size));
                tag.layoutBorderSize = 1f;
                tag.layoutBorderColor = getResources().getColor(android.R.color.transparent);
                tag.isDeletable = canDelete;
                tagView.addTag(tag);
            }
        }
    }


    /**
     * 获取List<SelectDataI> 的逗号分隔值
     *
     * @param items
     * @return
     */
    public String getListSplit(List<SelectDataI> items) {
        String res = "";
        Set<String> resultSet = new HashSet<>();
        for (int i = 0; items != null && i < items.size(); i++) {
            resultSet.add(items.get(i).getValue());
        }
        res = StringUtils.getSetString(resultSet);
        return res;
    }


    /****************************************************************************************************************
     * 音频播放
     ****************************************************************************************************************/


    /**
     * 声音  *
     */
    private MediaPlayer mMediaPlayer;
    private boolean playState = false; // 录音的播放状态

    private Dialog mRecordDialog;

    private ImageView mIvDialogRecVolume;
    private Thread mRecordThread;
    private double voiceValue = 0.0; // 录音的音量值
    private TextView mTvDialogRecordTxt;
    private Button mBtnDialogStop;
    private AudioManager mAudioManager;

    /**
     * 播放声音用的 *
     */
    protected void playVoice(String url) {
        showVoiceDialog(1);
        if (!playState) {
            mMediaPlayer = new MediaPlayer();
            mMediaPlayer.setOnCompletionListener(this);
            mMediaPlayer.setOnErrorListener(this);
            mMediaPlayer.setOnPreparedListener(this);
            try {
                mMediaPlayer.setDataSource(url);
                mMediaPlayer.prepareAsync();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            stopPlay();
        }
    }

    // 录音时显示Dialog
    private void showVoiceDialog(int flag) {
        if (mRecordDialog == null) {
            mRecordDialog = new Dialog(this, R.style.VoiceDialogStyle);
            mRecordDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            mRecordDialog.getWindow()
                    .setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
            mRecordDialog.setContentView(R.layout.view_record_dialog);
            mRecordDialog.setCanceledOnTouchOutside(false);
            mIvDialogRecVolume = (ImageView) mRecordDialog.findViewById(R.id.record_dialog_img);
            mTvDialogRecordTxt = (TextView) mRecordDialog.findViewById(R.id.record_dialog_txt);
            mBtnDialogStop = (Button) mRecordDialog.findViewById(R.id.btn_stop);
            mBtnDialogStop.setText("关闭播放");
            mBtnDialogStop.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    stopPlay();
                    dismissDialog();
                }
            });
        }
        switch (flag) {
            case 1:
                mIvDialogRecVolume.setImageResource(R.drawable.record_cancel);
                mTvDialogRecordTxt.setText("音频加载中...");
                break;

            default:
                mIvDialogRecVolume.setImageResource(R.drawable.record_animate_01);
                mTvDialogRecordTxt.setText("");
                break;
        }
        mTvDialogRecordTxt.setTextSize(ViewUtils.px2dip(IApplication.context(), getResources().getDimensionPixelSize(R.dimen.common_text_size)));
        //dismissDialog();
        mRecordDialog.show();
    }


    public Handler recordHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            AudioRecorder.voiceImageChange(voiceValue, mIvDialogRecVolume);
        }
    };

    private void dismissDialog() {
        if (mRecordDialog != null && mRecordDialog.isShowing()) {
            mRecordDialog.dismiss();
        }
    }

    // 录音计时线程
    void recordTimeThread() {
        mRecordThread = new Thread(recordThread);
        mRecordThread.start();
    }

    // 播放线程
    private Runnable recordThread = new Runnable() {

        @Override
        public void run() {
            int i = 1;
            while (playState) {
                i++;
                try {
                    Thread.sleep(150);
                    int max = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
                    int current = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
                    if (i % 2 == 0) {
                        voiceValue = (max + 1) * 599;
                    } else {
                        voiceValue = (current - 1) * 599;
                    }
                    recordHandler.sendEmptyMessage(1);
                } catch (InterruptedException e) {
                    if (BuildConfig.DEBUG) {
                        e.printStackTrace();
                    }
                }
            }
        }
    };

    @Override
    public void onCompletion(MediaPlayer mp) {
        stopPlay();
        dismissDialog();
        // 设置播放结束时监听
    }


    @Override
    public boolean onError(MediaPlayer mp, int what, int extra) {
        dismissDialog();
        mHUDUtil.showErrorTip("播放失败");
        return false;

    }

    @Override
    public void onPrepared(MediaPlayer mp) {
        playState = true;
        mMediaPlayer.start();
        recordTimeThread();
    }


    private void stopPlay() {
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            playState = false;
        } else {
            playState = false;
        }

        try {
            if (mRecordThread == null) {
                return;
            }
            mRecordThread.interrupt();
            voiceValue = 0.0;
        } catch (Exception e) {
            //e.printStackTrace();
        }
    }

    /**
     * 调用佳能打印App，打印文书
     */
    public void callPrinter(File file) {

        if (CheckAppExist.checkCanonPrinterExist(BaseActivity.this)) {
            ComponentName comp = new ComponentName("jp.co.canon.bsd.ad.pixmaprint", "jp.co.canon.bsd.ad.pixmaprint.EulaActivity");
            Intent intent = new Intent();
            intent.addCategory("android.intent.category.DEFAULT");
            intent.setComponent(comp);
            intent.setAction("android.intent.action.SEND");
            intent.setDataAndType(Uri.fromFile(file), "application/pdf");
            startActivity(intent);
        } else {
            getPrinterApk();
        }
    }

    public void getPrinterApk() {
        mHUDUtil.showHUD("您的手机未安装佳能打印工具，已开始为您自动下载，请耐心等待...");
        OkHttpUtils
                .get()
                //.url(UrlFormatUtils.formatFiles("")) //TODO 文件地址
                .url("http://a.gdown.baidu.com/data/wisegame/948be541d24a3f81/PRINT_235.apk?from=a1101") //TODO 文件地址
                .build()
                .execute(new FileCallBack(FileUtil.getAppDocTempDir(BaseActivity.this), Constants.APP_CANON_PRINTER_FILE_NAME) {

                    @Override
                    public void onError(Call call, Exception e) {
                        mHUDUtil.showErrorTip("获取安装文件失败。");
                    }

                    @Override
                    public void onResponse(File response) {
                        final File file = response;
                        mHUDUtil.showDoneTip("请根据系统提示安装打印工具，安装完成后返回，再尝试打印文书。", new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {
                                installApk(file);
                            }
                        });
                    }

                    @Override
                    public void inProgress(float progress, long total) {

                    }
                });
    }

    /**
     * 安装apk
     * @param apkFile
     */
    private void installApk(File apkFile) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(apkFile),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }

}


/**
 * 设置menu显示icon
 */

    /*
    @Override
    public boolean onMenuOpened(int featureId, Menu menu) {
        if (menu != null) {
            if (menu.getClass().getSimpleName().equals("MenuBuilder")) {
                try {
                    Method m = menu.getClass().getDeclaredMethod("setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        return super.onMenuOpened(featureId, menu);
    }
    */


